//
//  CompositionViewController.swift
//  AVCam
//
//  Created by 陈学明 on 2021/4/8.
//  Copyright © 2021 Apple. All rights reserved.
//

import UIKit

class CompositionViewController: UIViewController {
    var origin:Data
    var mask:Data
    var semanticSegmentationMatteDatas:[Data]
    var compositionImageView = UIImageView()
    
    
    init(origin:Data, mask:Data, semanticSegmentationMatteDatas: [Data]) {
        self.origin = origin
        self.mask = mask
        self.semanticSegmentationMatteDatas = semanticSegmentationMatteDatas
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        view.backgroundColor = .white
        
        let containerView = UIStackView()
        let size = view.frame.size
        containerView.frame = CGRect(x: 0, y: size.height - 330, width: size.width, height: 100)
        containerView.axis = .horizontal
        containerView.alignment = .fill
        containerView.distribution = .fillEqually
        containerView.spacing = 5
        
        view.addSubview(containerView)
        
        
        let originImageView =  UIImageView(image: UIImage(data: origin))
        originImageView.isUserInteractionEnabled = true
        originImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageClicked(_:))))
        containerView.addArrangedSubview(originImageView)
        
        let maskImageView =  UIImageView(image: UIImage(data: mask))
        maskImageView.isUserInteractionEnabled = true
        containerView.addArrangedSubview(maskImageView)
        maskImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageClicked(_:))))
        
        for item in semanticSegmentationMatteDatas {
            let imageView =  UIImageView(image: UIImage(data: item))
            imageView.isUserInteractionEnabled = true
            containerView.addArrangedSubview(imageView)
            imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageClicked(_:))))
        }
        
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        btn.center = CGPoint(x: view.center.x, y: containerView.frame.maxY + 50)
        btn.backgroundColor = .blue
        btn.setTitle("合成", for: .normal)
        btn.addTarget(self, action: #selector(handle), for: .touchUpInside)
        view.addSubview(btn)
        
        let w = size.width - 40
        let h = w * (originImageView.image!.size.height/originImageView.image!.size.width)
        compositionImageView.frame = CGRect(x: 20, y: 40, width: w, height: h)
        view.addSubview(compositionImageView)
        compositionImageView.image = originImageView.image
    }
    
    @objc func imageClicked(_ gesture:UITapGestureRecognizer) {
        let imageView = gesture.view as! UIImageView
        compositionImageView.image = imageView.image
        
    }
    
    @objc func handle() {
        var maskImage = renderImage(data: mask, color: nil)
        let alphaFilter = CIFilter(name: "CIMaskToAlpha", parameters: [kCIInputImageKey: maskImage])
        maskImage = alphaFilter!.outputImage!
        let inputImage = renderImage(data: origin, color: nil)
        let backgroundImage = renderImage(data: nil, color: .blue)
        var parameters = [String: Any]()
        parameters[kCIInputImageKey] = inputImage
        parameters[kCIInputBackgroundImageKey] = backgroundImage
        parameters[kCIInputMaskImageKey] = maskImage
        let filter = CIFilter(name: "CIBlendWithAlphaMask", parameters: parameters)
        print(filter?.attributes ?? ">>")
        if let res = filter?.outputImage {
            compositionImageView.image = UIImage(ciImage: res)
        }
    }
    
    func renderImage(data: Data?, color: UIColor?) -> CIImage {
        var uiimage:UIImage?
        if data != nil {
            uiimage = UIImage(data: data!)
        }
        let renderer = UIGraphicsImageRenderer(size: compositionImageView.frame.size)
        let image = renderer.image { (context) in
            context.cgContext.addRect(context.format.bounds)
            color?.setFill()
            context.cgContext.closePath()
            context.cgContext.drawPath(using: .fill)
            uiimage?.draw(in: context.format.bounds)
        }
        return CIImage(image: image)!
    }
}
